import 'package:dio/dio.dart';
import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:flutter_syt/api/api.dart';
import 'package:flutter_syt/application.dart';
import 'package:flutter_syt/datas/epidemic_item.dart';
import 'package:flutter_syt/datas/user_info.dart';
import 'package:flutter_syt/domain/test/nucleic_acid_report.dart';
import 'package:flutter_syt/generated/l10n.dart';
import 'package:flutter_syt/root_widget.dart';
import 'package:flutter_syt/routes.all.dart';
import 'package:flutter_syt/theme/font_styles.dart';
import 'package:flutter_syt/theme/theme_color.dart';
import 'package:flutter_syt/utils/click_utils.dart';
import 'package:flutter_syt/utils/screen_adapter.dart';
import 'package:flutter_syt/utils/utils_other.dart';
import 'package:flutter_syt/widgets/qr_code_view.dart';
import 'package:flutter_syt/widgets/view_state_widget.dart';
import 'package:flutter_syt/widgets/web_detail.dart';
import 'package:yyy_route_annotation/yyy_route_annotation.dart';

import '../../global_easy_loading.dart';

class BoxItemEntity {
  late String title;
  late String imageUrl;
  late String content;
  late GestureTapCallback onTap;

  BoxItemEntity(this.title, this.imageUrl, this.content, this.onTap);
}

class TagItemEntity {
  late String title;
  late String imageUrl;
  late GestureTapCallback onTap;

  TagItemEntity(this.title, this.imageUrl, this.onTap);
}

Map colorsArr = {
  '1': Colors.green[400],
  '2': Colors.yellow[400],
  '3': Colors.red[400]
};

@RoutePage(name: "epidemicHome")
class EpidemicHome extends StatefulWidget {
  @override
  _EpidemicHomeState createState() => _EpidemicHomeState();
}

class _EpidemicHomeState extends State<EpidemicHome>
    with TickerProviderStateMixin {
  late AnimationController _colorAnimationController;
  // AnimationController？ _textAnimationController;
  late Animation _colorTween;
  // Animation<Offset>? _transTween;

  bool isLogin = UserInfo.me.isLogin;
  bool isloading = true;
  EpidemicQRCode? qrCode;
  EpidemicData? epicData;
  EpidemicHSData? hssjData;
  EpidemicYMData? ymjkData;
  String? error;
  @override
  void initState() {
    if (UserInfo.me.isLogin) {
      _getqrCode();
      _initInfo();
    }
    _colorAnimationController =
        AnimationController(vsync: this, duration: Duration(seconds: 0));
    _colorTween = ColorTween(begin: Colors.transparent, end: Colors.white)
        .animate(_colorAnimationController);

    super.initState();
  }

  bool _scrollListener(ScrollNotification scrollInfo) {
    if (scrollInfo.metrics.axis == Axis.vertical &&
        scrollInfo.metrics.pixels < 100) {
      _colorAnimationController.animateTo(scrollInfo.metrics.pixels / 40);
      return true;
    }
    return false;
  }

  Future _getqrCode() async {
    EpidemicQRCode qr = await API.shared.epidemic.qrCode();
    setState(() {
      qrCode = qr;
    });
  }

  Future _initInfo() async {
    try {
      EpidemicData data = await API.shared.epidemic.data();
      EpidemicHSData hsdata = await API.shared.epidemic.hssjData();
      EpidemicYMData ymData = await API.shared.epidemic.ymjkData();
      error = null;
      setState(() {
        epicData = data;
        hssjData = hsdata;
        ymjkData = ymData;
        isloading = false;
      });
    } catch (e) {
      // EasyLoading.dismiss();
      await UtilsOther.showCustomShowError(e);
      // setState(() {
      //   if (e is DioError) {
      //     error = e.message;
      //   } else {
      //     error = S.of(context).network_error;
      //   }
      // });
    }
  }

  Widget loading() {
    return Container(
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Image.asset(
            "assets/icons/empty.png",
            width: 80,
            height: 80,
          ),
          Container(
            height: 12,
          ),
          Text(
            S.of(context).loading,
            style:
                TextStyle(color: Colors.black.withOpacity(0.4), fontSize: 14),
          ),
          Container(
            height: 20,
          ),
        ],
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    List<TagItemEntity> boxList = [
      TagItemEntity(
        S.of(context).submit_nucleic_acid_test_result,
        "assets/images/hsbg.png",
        () {
          var ctx = navigatorKey.currentContext;
          if (ctx != null) {
            if (!UserInfo.me.isLogin) {
              RouteManager.push(ctx, RoutMapping.loginByPwd());
              return;
            }
            Navigator.of(ctx).push(MaterialPageRoute(
                builder: (bld) => NucleicAcidReportPage(true)));
          }
        },
      ),
      TagItemEntity(
        S.of(context).submit_covid_19_vaccination_information,
        "assets/images/ymjzjl.png",
        () {
          var ctx = navigatorKey.currentContext;
          if (ctx != null) {
            if (!UserInfo.me.isLogin) {
              RouteManager.push(ctx, RoutMapping.loginByPwd());
              return;
            }
            Navigator.of(ctx).push(MaterialPageRoute(
                builder: (bld) => NucleicAcidReportPage(false)));
          }
        },
      ),
      TagItemEntity(
        S.of(context).Travel_Card,
        "assets/images/xck.png",
        () {
          Navigator.push(
              context,
              MaterialPageRoute(
                  builder: (context) => WebDetailPage(
                      'https://xc.caict.ac.cn/?code=116&amp;amp;amp;phone#/login')));
        },
      ),
      TagItemEntity(
        S.of(context).Health_publicity,
        "assets/images/jkxc.png",
        () {
          // customShowToast(S().standy_by);

          RouteManager.push(
            context,
            RoutMapping.epidemicHealthListPage(type: 0),
          );
        },
      ),
      TagItemEntity(
        S.of(context).Prevention_information,
        "assets/images/fyxx.png",
        () {
          // customShowToast(S().standy_by);
          RouteManager.push(
            context,
            RoutMapping.epidemicHealthListPage(type: 1),
          );
        },
      ),
      TagItemEntity(
        S.of(context).knowledge,
        "assets/images/jkzsk.png",
        () {
          // customShowToast(S().standy_by);
          RouteManager.push(
            context,
            RoutMapping.epidemicHealthListPage(type: 2),
          );
        },
      )
    ];
    var showLoading = false;
    if (isloading && isLogin) {
      showLoading = true;
    }

    var content = Stack(
      children: [
        Positioned(
          top: 0,
          left: 0,
          right: 0,
          child: Container(
            width: double.infinity,
            child: Image.asset(
              'assets/images/epi_home.png',
              width: double.infinity,
            ),
          ),
        ),
        NotificationListener<ScrollNotification>(
            onNotification: _scrollListener,
            child: Container(
              padding: EdgeInsets.only(left: 16, right: 16),
              child: ListView(
                physics: ClampingScrollPhysics(),
                children: [
                  Container(
                    height: 90,
                  ),
                  Stack(
                    clipBehavior: Clip.none,
                    children: [
                      Container(
                        // padding: EdgeInsets.only(bottom: 20),
                        width: double.infinity,
                        child: Column(
                          children: [
                            Container(
                              height: 56,
                              // padding: EdgeInsets.only(top: 12),
                              decoration: BoxDecoration(
                                color: ThemeColor.bkColorFFFFFF,
                                // color: Colors.red,
                                borderRadius: BorderRadius.only(
                                    topLeft: Radius.circular(12),
                                    topRight: Radius.circular(12)),
                              ),
                              child: GestureDetector(
                                onTap: ClickUtils.debounce(() {
                                  if (!isLogin) {
                                    RouteManager.push(
                                      context,
                                      RoutMapping.loginByPwd(),
                                    );
                                  }
                                }),
                                child: Row(
                                  // crossAxisAlignment: CrossAxisAlignment.center,
                                  children: isLogin
                                      ? [
                                          SizedBox(
                                            width: 24,
                                          ),
                                          Expanded(
                                            child: Text(
                                              S.of(context).user_nickname,
                                              textAlign: TextAlign.left,
                                              style: TextStyle(
                                                color: ThemeColor.colorBlack100,
                                                fontSize: 18,
                                                fontWeight: FontWeight.w500,
                                              ),
                                              softWrap: false,
                                              overflow: TextOverflow.ellipsis,
                                            ),
                                          )
                                        ]
                                      : [
                                          SizedBox(
                                            width: 24,
                                          ),
                                          Text(
                                            "${isLogin ? S.of(context).user_nickname : S.of(context).Log_in}",
                                            // textAlign: TextAlign.center,
                                            // style: TextStyle(
                                            //   color: ThemeColor.colorBlack100,
                                            //   fontSize: 16,
                                            //   fontWeight: FontWeight.w400,
                                            // ),
                                          ),
                                          // SizedBox(
                                          //   width: 8,
                                          // ),
                                          // SizedBox(
                                          //   width: 10,
                                          //   child: Image.asset(
                                          //     'assets/icons/icon_right_black.png',
                                          //     width: 10,
                                          //   ),
                                          // )
                                          Container(
                                            height: 20,
                                            padding: EdgeInsets.only(left: 8),
                                            // color: Colors.red,
                                            alignment: Alignment.center,
                                            child: Image.asset(
                                              'assets/icons/icon_right_black.png',
                                              width: 10,
                                            ),
                                          ),
                                        ],
                                ),
                              ),
                            ),
                            // isLogin && (qrCode?.qrCode ?? '') != ''
                            // ? Column(
                            //     children: [
                            //       Container(
                            //         margin:
                            //             EdgeInsets.only(top: 26, bottom: 8),
                            //         width: 180,
                            //         height: 180,
                            //         decoration: BoxDecoration(
                            //           borderRadius: BorderRadius.circular(12),
                            //           color: ThemeColor.bkColorFFFFFF,
                            //           image: DecorationImage(
                            //             image: NetworkImage(
                            //               qrCode?.qrCode ?? '',
                            //             ),
                            //             fit: BoxFit.cover,
                            //           ),
                            //         ),
                            //         alignment: Alignment.center,
                            //       ),
                            //       Container(
                            //         margin: EdgeInsets.only(bottom: 15),
                            //         child: Text(
                            //           qrCode?.message ?? '',
                            //           style: TextStyle(
                            //               fontSize: 12,
                            //               color: colorsArr[
                            //                   qrCode?.status ?? '1']),
                            //         ),
                            //       )
                            //     ],
                            //   )
                            // : Container(
                            //     margin: EdgeInsets.only(top: 26, bottom: 15),
                            //     width: 180,
                            //     height: 180,
                            //     decoration: BoxDecoration(
                            //       borderRadius: BorderRadius.circular(12),
                            //       color: ThemeColor.bkColorFFFFFF,
                            //       image: DecorationImage(
                            //         image: AssetImage(
                            //           'assets/images/notlogincode.png',
                            //         ),
                            //         fit: BoxFit.cover,
                            //       ),
                            //     ),
                            //     alignment: Alignment.center,
                            //     child: isLogin
                            //         ? Text('暂无数据，请稍后重试')
                            //         : Text('未登录，暂无数据'),
                            //   ),
                            Container(
                              width: double.infinity,
                              height: 25,
                              child: Image.asset(
                                'assets/images/epi_line_bg.png',
                                fit: BoxFit.fill,
                              ),
                            ),
                            Container(
                              decoration: BoxDecoration(
                                color: ThemeColor.bkColorFFFFFF,
                                borderRadius: BorderRadius.only(
                                    bottomLeft: Radius.circular(12),
                                    bottomRight: Radius.circular(12)),
                              ),
                              padding: EdgeInsets.only(bottom: 20),
                              child: Column(
                                children: [
                                  Padding(
                                    padding: EdgeInsets.only(
                                      top: 12,
                                      left: 40,
                                      right: 40,
                                      bottom: 20,
                                    ),
                                    child: ElevatedButton(
                                      child: Text(
                                        S.of(context).scan_location_qr_code,
                                        style: TextStyle(
                                            fontWeight: FontWeight.bold),
                                      ),
                                      onPressed: ClickUtils.debounce(
                                        () async {
                                          customShowToast(S().standy_by);
                                          //TODO:扫码
                                          // var result =
                                          //     await Navigator.of(this.context).push(
                                          //   MaterialPageRoute(
                                          //     builder: (context) => QRCodePage(),
                                          //   ),
                                          // );
                                        },
                                      ),
                                    ),
                                  ),
                                  GestureDetector(
                                    onTap: ClickUtils.debounce(() {
                                      if (!isLogin) {
                                        RouteManager.push(
                                          context,
                                          RoutMapping.loginByPwd(),
                                        );
                                      } else {
                                        RouteManager.push(
                                          context,
                                          RoutMapping.epidemicPage(),
                                        );
                                      }
                                    }),
                                    child: Container(
                                      margin: EdgeInsets.only(
                                        left: 40,
                                        right: 40,
                                        bottom: 32,
                                      ),
                                      alignment: Alignment.center,
                                      height: 48,
                                      decoration: BoxDecoration(
                                        borderRadius: BorderRadius.circular(8),
                                        border: Border.all(
                                          width: 1,
                                          color: Color(0xffdfdfdf),
                                        ),
                                      ),
                                      child: Text(
                                        '${S.of(context).health_punch_in}：${epicData?.isReported.message ?? S.of(context).Undone}',
                                        style: TextStyle(
                                          fontSize: 14,
                                          color: ThemeColor.colorBlack80,
                                          fontWeight: FontWeight.w500,
                                        ),
                                      ),
                                    ),
                                  ),
                                  Row(
                                    mainAxisAlignment:
                                        MainAxisAlignment.spaceEvenly,
                                    children: [
                                      _infoBox(BoxItemEntity(
                                        S.of(context).nucleic_acid_test,
                                        'assets/images/epi_bk_blue.png',
                                        (hssjData?.hsjcjg ?? '') == ''
                                            ? S.of(context).no_content
                                            : hssjData!.hsjcjg,
                                        () {
                                          if (!isLogin) {
                                            RouteManager.push(
                                              context,
                                              RoutMapping.loginByPwd(),
                                            );
                                          }
                                        },
                                      )),
                                      _infoBox(BoxItemEntity(
                                        S.of(context).covid_19_vaccines,
                                        'assets/images/epi_bk_green.png',
                                        (ymjkData?.sfjzwc ?? '') == ''
                                            ? S().no_content
                                            : ymjkData?.sfjzwc == '1'
                                                ? S().vacc_complete
                                                : S().vacc_incomplete,
                                        () {
                                          if (!isLogin) {
                                            RouteManager.push(
                                              context,
                                              RoutMapping.loginByPwd(),
                                            );
                                          }
                                        },
                                      )),
                                    ],
                                  ),
                                ],
                              ),
                            )
                            // Container(
                            //   height: 10,
                            // ),
                            // Row(
                            //   mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                            //   children: [
                            //     _infoBox(
                            //       BoxItemEntity(
                            //         '健康打卡',
                            //         'assets/images/epi_bk_orange.png',
                            //         epicData?.isReported.message ?? "暂无数据",
                            //         () {
                            //           if (!isLogin) {
                            //             RouteManager.push(
                            //               context,
                            //               RoutMapping.loginByPwd(),
                            //             );
                            //           } else {
                            //             RouteManager.push(
                            //               context,
                            //               RoutMapping.epidemicPage(),
                            //             );
                            //           }
                            //         },
                            //       ),
                            //     ),
                            //     _infoBox(BoxItemEntity(
                            //       S.of(context).covid_19_and_health,
                            //       'assets/images/epi_bk_pink.png',
                            //       epicData?.epidemic.message ?? "暂无数据",
                            //       () {
                            //         if (!isLogin) {
                            //           RouteManager.push(
                            //             context,
                            //             RoutMapping.loginByPwd(),
                            //           );
                            //         }
                            //       },
                            //     )),
                            //   ],
                            // )
                          ],
                        ),
                      ),
                    ],
                  ),
                  Container(
                    margin: EdgeInsets.only(top: 10),
                    padding: EdgeInsets.only(top: 20, bottom: 20),
                    width: double.infinity,
                    decoration: BoxDecoration(
                      color: ThemeColor.bkColorFFFFFF,
                      borderRadius: BorderRadius.circular(12),
                    ),
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      children: [
                        Container(
                          alignment: Alignment.centerLeft,
                          margin: EdgeInsets.only(left: 16, bottom: 20),
                          child: Text(S.of(context).other_services,
                              style: FontStyles.headerTextStyle_18
                                  .copyWith(fontWeight: FontWeight.w500)),
                        ),
                        Wrap(
                          spacing: 26,
                          runSpacing: 10,
                          children: boxList
                              .map((e) => GestureDetector(
                                    // onTap: e.onTap,
                                    onTap: ClickUtils.debounce(() => e.onTap),
                                    child: Container(
                                      alignment: Alignment.center,
                                      width:
                                          (ScreenAdapter.screenW() - 32.0) / 4,
                                      child: _iconText(e.imageUrl, e.title),
                                    ),
                                  ))
                              .toList(),
                        ),
                      ],
                    ),
                  ),
                  // Container(
                  //   height: 390,
                  // ),
                ],
              ),
            )),
        Container(
            height: 64 + ScreenUtil().statusBarHeight,
            child: AnimatedBuilder(
              animation: _colorAnimationController,
              builder: (context, child) {
                return AppBar(
                    backgroundColor: _colorTween.value,
                    elevation: 0,
                    titleSpacing: 0.0,
                    title: Text(
                      S.current.covid_19,
                    ));
              },
            ))
        // Positioned(
        //     top: 20 + ScreenUtil().statusBarHeight,
        //     left: 16,
        //     right: 16,
        //     child: Container(
        //       // color: Colors.red,
        //       child: Row(
        //         mainAxisAlignment: MainAxisAlignment.spaceBetween,
        //         children: [
        //           SizedBox(
        //             width: 44,
        //             height: 44,
        //             child: BackButton(),
        //           ),
        //           Text(
        //             S.current.covid_19,
        //             style: FontStyles.headerTextStyle_18,
        //           ),
        //           SizedBox(
        //             width: 44,
        //             height: 44,
        //           )
        //         ],
        //       ),
        //     )),
      ],
    );
    Widget getBody() {
      if (error != null) {
        return ViewStateErrorWidget(onPressed: _initInfo);
      } else if (showLoading) {
        return loading();
      } else {
        return content;
      }
    }

    var color = Colors.white;
    if (error == null) {
      color = Color(0xffF5B11C);
    }
    return Scaffold(
      // appBar: AppBar(
      //   leading: IconButton(
      //     icon: Image.asset(
      //       "assets/images/black_back.png",
      //       width: 30,
      //       height: 30,
      //     ),
      //     onPressed: () {
      //       Navigator.of(context).pop();
      //     },
      //   ),
      // ),
      backgroundColor: showLoading == true ? Colors.white : color,
      body: getBody(),
    );
  }

  Widget _infoBox(BoxItemEntity data) {
    return GestureDetector(
      onTap: ClickUtils.debounce(() => data.onTap),
      child: Container(
        width: 150,
        height: 100,
        padding: EdgeInsets.fromLTRB(10, 5, 10, 5),
        decoration: BoxDecoration(
          image: DecorationImage(
            image: AssetImage(
              data.imageUrl,
            ),
            fit: BoxFit.cover,
          ),
        ),
        child: Column(
          children: [
            Row(
              children: [
                Text(
                  data.title,
                  textAlign: TextAlign.center,
                  style: TextStyle(
                    color: ThemeColor.colorBlack80,
                    fontSize: 12,
                    fontWeight: FontWeight.w500,
                  ),
                ),
                Container(
                  padding: EdgeInsets.only(top: 4, left: 8),
                  alignment: Alignment.center,
                  child: Image.asset(
                    'assets/icons/icon_right_black.png',
                    width: 6,
                  ),
                ),
              ],
            ),
            Padding(
              padding: EdgeInsets.only(top: 30),
              child: Text(
                data.content,
                style: TextStyle(
                  fontSize: 18,
                  color: ThemeColor.colorBlack80,
                  fontWeight: FontWeight.w400,
                ),
              ),
            ),
          ],
        ),
      ),
    );
  }

  Widget _iconText(String url, String text) {
    return Column(
      mainAxisSize: MainAxisSize.min,
      children: [
        Image.asset(
          url,
          width: 52,
        ),
        Container(
          margin: EdgeInsets.only(top: 8),
          child: Text(
            text,
            textAlign: TextAlign.center,
            style: TextStyle(
              fontSize: 12,
              color: ThemeColor.colorBlack100,
              fontWeight: FontWeight.w300,
            ),
          ),
        ),
      ],
    );
  }
}
